import { activate, update } from '@/api/rule'

// 激活/应用
export function submitApi() {
  this.active = this.active || localStorage.modelType
  let data = this.data
  let row = this.row
  let flag = true
  let params = {
    id: data.id,
    poltype: this.poltype,
    // ruleApplicationDistrictName: '',
    // ruleApplicationDistrictNo: '',
    warningModelId: data.warningModelId,
    warningRuleThresholdList: []
  }
  if (this.active != 5) { // 类型1-4
    params.ruleStatus = this.form?.status == '已激活' ? 1 : 0
    params.warningRuleThresholdList = [
      {
        warningThreshold: this.form.valve,
        ruleLevelStatus: this.form?.level ? 1 : 0,
        warningRuleLevelList: []
      }
    ]
    this.levels.map((i) => {
      params.warningRuleThresholdList[0].warningRuleLevelList.push({
        levelName: i.name,
        beginInterval: i.min,
        endInterval: i.max,
        fileUrl: i.imageUrl
      })
    })
  } else { // 高发类型5
    params.id = row.id
    params.warningModelId = row.warningModelId
    params.ruleStatus = row.ruleStatus
    params.ruleLevelStatus = row.ruleLevelStatus
    // params.ruleApplicationDistrictName = row.ruleApplicationDistrictName
    // params.ruleApplicationDistrictNo = row.ruleApplicationDistrictNo

    data.map(i => {
      let warningRuleLevelList = []
      if (i.isLevel && i.levels?.length) {
        i.levels.map(j => {
          if (j.name && j.min && j.max) {
            warningRuleLevelList.push({
              levelName: j.name,
              beginInterval: j.min,
              endInterval: j.max,
              fileUrl: j.imageUrl
            })
          }
        })
      }
      if (i.eventType && i.dateType && i.num) {
        params.warningRuleThresholdList.push({
          id: i?.id,
          eventType: i.eventType,
          warningRange: i.dateType,
          warningRuleId: '',
          ruleLevelStatus: i.isLevel ? 1 : 0,
          warningThreshold: i.num,
          warningRuleLevelList
        })
      } else {
        this.$message.warning('请输入正确的预警阀值')
        flag = false
      }
    })
  }
  let api = ''
  let msg = ''
  let status = ''
  if (this.data) {
    status = this.data.ruleStatus
  } else {
    status = this.row.ruleStatus
  }
  if (status == 1) {
    api = update
    msg = '应用成功'
  } else {
    api = activate
    msg = '激活成功'
  }
  if (flag) {
    api(params).then((res) => {
      if (!res.success) return
      this.$message.success(msg)
      this.visible = false
      this.FormDialogVisible = false
      this.findByModelId && this.findByModelId()
      this.handleSearch && this.handleSearch()
    })
  }
}
